package typejump;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Hashtable;

import typejump.commands.DevGrab;
import typejump.engine.GameEngine;
import typejump.objects.Actor;

/**
 * This class handles InputEvents from the game canvas and makes stuff happen
 * (eg, reading commands from key presses and sending them to the GameEngine)
 * @author g
 *
 */
public class PlayerCommands implements KeyListener, MouseListener {

	private TypeJump parent;
	private Hashtable<Integer, Boolean> keyDownTable = new Hashtable<Integer, Boolean>();
	
	private StringBuffer commandBuffer = new StringBuffer(10);
		
	
	public PlayerCommands(TypeJump parent) {
		this.parent = parent;
	}
	
	public boolean isKeyDown(int code) {
		if (keyDownTable.containsKey(code)) {
			return keyDownTable.get(code);
		}
		return false;
	}
	
	private void setKeyDown(int code, boolean b) {
		keyDownTable.put(code, b);
	}
	
	private boolean isNormal(char c) {
		if (c >= 32 && c <= 126) return true;
		return false;
	}
	
	public void keyPressed(KeyEvent e) {
		int code = e.getKeyCode();
		char c = e.getKeyChar();
		setKeyDown(code, true);
		
		Actor p = parent.getPlayer();
			
		Messenger.addBriefMessage("keydown " + code);
		
		if (isNormal(c)) {
			commandBuffer.append(c);
		} else if (code == KeyEvent.VK_ENTER) {
			String command = commandBuffer.toString().trim();
			commandBuffer.setLength(0);
			processCommand(command);
		} else if (code == KeyEvent.VK_BACK_SPACE) {
			commandBuffer.setLength(Math.max(0, commandBuffer.length()-1));
		} else if (code == KeyEvent.VK_DELETE) {
			if (TypeJump.getInst().isShowingEditor()) {
				GameEngine.addCommand("dev delete");
			}
		}
		
		parent.setDisplayedCommand(commandBuffer.toString());
	}
	public void keyReleased(KeyEvent e) {
		int code = e.getKeyCode();
		setKeyDown(code, false);
		
		Messenger.addBriefMessage("keyup " + code);
	}
	public void keyTyped(KeyEvent e) {
		
	}
	
	public void processCommand(String command) {		
		GameEngine.addCommand(command);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if (TypeJump.getInst().isShowingEditor()) {
			if (!GameEngine.isHappening(DevGrab.class))
				GameEngine.addCommand("dev grab");
			else
				Messenger.addBriefMessage("mouse click");
		} else {
			Messenger.addBriefMessage("mouse click");
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		Messenger.addBriefMessage("mouse press");
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		Messenger.addBriefMessage("mouse release");
	}
}
